package com.beyondsoft.sabg.edu.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.aimiaobi20230801.Client;
import com.aliyun.aimiaobi20230801.models.*;
import com.aliyun.teautil.models.RuntimeOptions;
import com.beyondsoft.sabg.edu.config.AiMiaoBiConfig;
import com.beyondsoft.sabg.edu.model.dto.DocumentFormFieldsDto;
import com.beyondsoft.sabg.edu.model.dto.DocumentOperationRequestDto;
import com.beyondsoft.sabg.edu.model.vo.AiMiaoBiAuditResultVO;
import com.beyondsoft.sabg.edu.service.AiMiaoBiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 阿里云妙笔服务实现类
 */
@Service
@Slf4j
public class AiMiaoBiServiceImpl implements AiMiaoBiService {

    @Autowired
    private Client aiMiaoBiClient;

    @Autowired
    private AiMiaoBiConfig aiMiaoBiConfig;

    @Value("${aliyun.access-key-id:LTAI5t6Aai4r2JPzSjgyBJD6}")
    private String accessKeyId;

    @Value("${aliyun.access-key-secret:1tN58olM4spneH2JTjSkxQWu4GfxQ1}")
    private String accessKeySecret;

    // 字段中文名称映射
    private static final Map<String, String> FIELD_NAME_MAP = new HashMap<>();

    static {
        FIELD_NAME_MAP.put("title", "标题");
        FIELD_NAME_MAP.put("reason", "缘由");
        FIELD_NAME_MAP.put("matter", "事项");
        FIELD_NAME_MAP.put("issuingAuthority", "发文机关");
        FIELD_NAME_MAP.put("mainRecipient", "主送机关");
        FIELD_NAME_MAP.put("conclusion", "结语");
        FIELD_NAME_MAP.put("issueDate", "发文日期");
        FIELD_NAME_MAP.put("mainFacts", "主要事实");
        FIELD_NAME_MAP.put("decisionRequirements", "决定要求");
        FIELD_NAME_MAP.put("educationalSignificance", "教育意义");
        FIELD_NAME_MAP.put("requirements", "要求");
        FIELD_NAME_MAP.put("resolutionRequirements", "决议要求");
        FIELD_NAME_MAP.put("coreContent", "核心内容");
        FIELD_NAME_MAP.put("orderMatters", "命令事项");
        FIELD_NAME_MAP.put("quotedContent", "引述内容");
        FIELD_NAME_MAP.put("reply", "答复");
        FIELD_NAME_MAP.put("specificOpinions", "具体意见");
        FIELD_NAME_MAP.put("meetingOverview", "会议概况");
        FIELD_NAME_MAP.put("meetingSpirit", "会议精神");
        FIELD_NAME_MAP.put("meetingTime", "会议时间");
        FIELD_NAME_MAP.put("attendees", "出席");
        FIELD_NAME_MAP.put("leaveOfAbsence", "请假");
        FIELD_NAME_MAP.put("observers", "列席");
        FIELD_NAME_MAP.put("theme", "主题");
        FIELD_NAME_MAP.put("writingScenario", "写作场景");
        FIELD_NAME_MAP.put("wordCountRange", "字数限制");
        FIELD_NAME_MAP.put("mainSendingUnit", "主送单位");
        FIELD_NAME_MAP.put("documentDate", "发文时间");
        FIELD_NAME_MAP.put("meetingLocation", "会议地点");
        FIELD_NAME_MAP.put("participants", "参会人员");
        FIELD_NAME_MAP.put("issuingUnit", "发文单位");
    }

    @Override
    public String submitSmartAudit(DocumentOperationRequestDto request) throws Exception {
        String text = request.getFullDocumentContent();
        log.info("提交智能审查任务，文本长度：{}", text != null ? text.length() : 0);

        try {
            SubmitSmartAuditRequest auditRequest = new SubmitSmartAuditRequest()
                    .setWorkspaceId(aiMiaoBiConfig.getWorkspaceId())
                    .setText(text);

            RuntimeOptions runtime = new RuntimeOptions();
            SubmitSmartAuditResponse response = aiMiaoBiClient.submitSmartAuditWithOptions(auditRequest, runtime);

            log.info("智能审查任务提交完成，请求ID：{}", response.getBody().getRequestId());

            if (response.getBody().getSuccess()) {
                String taskId = response.getBody().getData().getTaskId();
                log.info("审查任务ID：{}", taskId);
                return taskId;
            } else {
                throw new RuntimeException("提交审查任务失败：" + response.getBody().getMessage());
            }

        } catch (Exception e) {
            log.error("提交智能审查任务失败", e);
            throw new RuntimeException("提交智能审查任务失败：" + e.getMessage(), e);
        }
    }

    @Override
    public AiMiaoBiAuditResultVO getSmartAuditResult(String taskId) throws Exception {
        log.info("获取智能审查结果，任务ID：{}", taskId);

        try {
            GetSmartAuditResultRequest request = new GetSmartAuditResultRequest()
                    .setWorkspaceId(aiMiaoBiConfig.getWorkspaceId())
                    .setTaskId(taskId);

            RuntimeOptions runtime = new RuntimeOptions();
            GetSmartAuditResultResponse response = aiMiaoBiClient.getSmartAuditResultWithOptions(request, runtime);

            log.info("获取智能审查结果完成，请求ID：{}", response.getBody().getRequestId());
            log.info("任务状态: {}, 错误详情数量: {}", 
                response.getBody().getData().getStatus(),
                response.getBody().getData().getErrorItemDetails() != null ? 
                    response.getBody().getData().getErrorItemDetails().size() : 0);

            if (response.getBody().getSuccess()) {
                AiMiaoBiAuditResultVO result = new AiMiaoBiAuditResultVO();
                result.setRequestId(response.getBody().getRequestId());
                result.setStatus(response.getBody().getData().getStatus());

                // 转换错误详情
                if (response.getBody().getData().getErrorItemDetails() != null) {
                    result.setErrorItemDetails(new ArrayList<>());
                    
                    for (var sdkErrorItem : response.getBody().getData().getErrorItemDetails()) {
                        AiMiaoBiAuditResultVO.ErrorItemDetail errorDetail = new AiMiaoBiAuditResultVO.ErrorItemDetail();
                        
                        try {
                            // 根据实际SDK字段结构进行映射
                            
                            // 基本字段映射
                            if (sdkErrorItem.getContext() != null) {
                                errorDetail.setOriginalText(sdkErrorItem.getContext());
                            }
                            
                            if (sdkErrorItem.getOffset() != null) {
                                errorDetail.setPosition(sdkErrorItem.getOffset());
                            }
                            
                            if (sdkErrorItem.getMajorCode() != null) {
                                errorDetail.setErrorType(sdkErrorItem.getMajorCode());
                                errorDetail.setMajorCode(sdkErrorItem.getMajorCode());
                            }
                            
                            // 详细字段映射
                            if (sdkErrorItem.getErrorWord() != null) {
                                errorDetail.setErrorWord(sdkErrorItem.getErrorWord());
                            }
                            
                            if (sdkErrorItem.getRightWord() != null) {
                                errorDetail.setRightWord(sdkErrorItem.getRightWord());
                                errorDetail.setSuggestedText(sdkErrorItem.getRightWord()); // 保持向后兼容
                            }
                            
                            if (sdkErrorItem.getContextOffset() != null) {
                                errorDetail.setContextOffset(sdkErrorItem.getContextOffset());
                            }
                            
                            if (sdkErrorItem.getErrorLevel() != null) {
                                errorDetail.setErrorLevel(sdkErrorItem.getErrorLevel());
                            }
                            
                            if (sdkErrorItem.getMajorCodeDesc() != null) {
                                errorDetail.setMajorCodeDesc(sdkErrorItem.getMajorCodeDesc());
                            }
                            
                            if (sdkErrorItem.getSubClassCode() != null) {
                                errorDetail.setSubClassCode(sdkErrorItem.getSubClassCode());
                            }
                            
                            if (sdkErrorItem.getSubClassDesc() != null) {
                                errorDetail.setSubClassDesc(sdkErrorItem.getSubClassDesc());
                            }
                            
                            if (sdkErrorItem.getReason() != null) {
                                errorDetail.setReason(sdkErrorItem.getReason());
                            }
                            
                            if (sdkErrorItem.getCheckId() != null) {
                                errorDetail.setCheckId(sdkErrorItem.getCheckId());
                            }
                            
                            // 组合错误描述：主要错误描述 + 具体原因
                            StringBuilder errorDesc = new StringBuilder();
                            if (sdkErrorItem.getMajorCodeDesc() != null) {
                                errorDesc.append(sdkErrorItem.getMajorCodeDesc());
                            }
                            if (sdkErrorItem.getReason() != null) {
                                if (errorDesc.length() > 0) {
                                    errorDesc.append("：");
                                }
                                errorDesc.append(sdkErrorItem.getReason());
                            }
                            if (sdkErrorItem.getSubClassDesc() != null && 
                                !sdkErrorItem.getSubClassDesc().equals(sdkErrorItem.getReason())) {
                                if (errorDesc.length() > 0) {
                                    errorDesc.append("（").append(sdkErrorItem.getSubClassDesc()).append("）");
                                }
                            }
                            errorDetail.setErrorDescription(errorDesc.toString());
                            
                            result.getErrorItemDetails().add(errorDetail);
                            
                            log.debug("转换错误项: 位置={}, 类型={}, 错误词={}, 建议词={}, 级别={}", 
                                errorDetail.getPosition(), 
                                errorDetail.getErrorType(),
                                errorDetail.getErrorWord(),
                                errorDetail.getRightWord(),
                                errorDetail.getErrorLevel());
                            
                        } catch (Exception e) {
                            log.error("转换错误详情失败: {}", e.getMessage(), e);
                        }
                    }
                }

                log.info("智能审查结果转换完成，状态: {}, 错误项数量: {}", 
                    result.getStatus(), 
                    result.getErrorItemDetails() != null ? result.getErrorItemDetails().size() : 0);
                
                return result;
            } else {
                throw new RuntimeException("获取审查结果失败：" + response.getBody().getMessage());
            }

        } catch (Exception e) {
            log.error("获取智能审查结果失败", e);
            throw new RuntimeException("获取智能审查结果失败：" + e.getMessage(), e);
        }
    }

    @Override
    public AiMiaoBiAuditResultVO smartAudit(DocumentOperationRequestDto request) throws Exception {
        String text = request.getFullDocumentContent();
        log.info("开始智能审查（同步），文本长度：{}", text != null ? text.length() : 0);

        try {
            // 提交审查任务
            String taskId = submitSmartAudit(request);

            // 轮询获取结果
            int maxRetries = 50; // 最大重试30次
            int retryInterval = 2000; // 每次间隔2秒

            for (int i = 0; i < maxRetries; i++) {
                Thread.sleep(retryInterval);

                AiMiaoBiAuditResultVO result = getSmartAuditResult(taskId);

                if ("SUCCESSED".equals(result.getStatus()) || "FAILED".equals(result.getStatus())) {
                    log.info("智能审查完成，状态：{}", result.getStatus());
                    return result;
                }

                log.info("审查任务进行中，第{}次检查，状态：{}", i + 1, result.getStatus());
            }

            throw new RuntimeException("智能审查超时，请稍后查询结果");

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("智能审查被中断", e);
        } catch (Exception e) {
            log.error("智能审查失败", e);
            throw new RuntimeException("智能审查失败：" + e.getMessage(), e);
        }
    }

    @Override
    public SseEmitter runWritingStream(DocumentOperationRequestDto request) throws Exception {
        log.info("开始智能写作流式返回，文档类型：法定公文类");
        
        SseEmitter emitter = new SseEmitter(300000L); // 5分钟超时
        
        CompletableFuture.runAsync(() -> {
            try {
                // 从request中提取参数
                DocumentFormFieldsDto fields = request.getDocumentFields();
                String wordCount = aiMiaoBiConfig.getGcNumberSizeTag(); // 默认字数
                if (StrUtil.isNotEmpty(fields.getWordCount())) {
                    wordCount = fields.getWordCount();
                }

                // 转换writingParams
                Map<String, String> writingParamsMap = convertFieldsToMap(fields);
                log.info("转换的writingParams: {}", writingParamsMap);
                // https://help.aliyun.com/zh/model-studio/api-aimiaobi-2023-08-01-runwritingv2
                RunWritingV2Request writeRequest = new RunWritingV2Request()
//                        .setArticles(Arrays.asList(articles)) //  引用的文章
                        .setWritingParams(writingParamsMap)  // 写作提示词（prompt 和 writingParams 二选一）
                        .setPrompt("你是一位精通Markdown格式的专业内容创作者。根据用户要求生成对应的文章，注意markdown标题格式的正确输出。" +
                                "标题：使用#（一级标题）、##（二级标题）、###（三级标题）等来创建不同级别的标题。\n" +
                                "\n" +
                                "列表：使用1.、2.等来创建有序列表。\n" +
                                "\n" +
                                "加粗/斜体：使用**文本**来加粗，使用*文本*或_文本_来斜体。")
                        .setWorkspaceId(aiMiaoBiConfig.getWorkspaceId())
                        .setWritingScene(aiMiaoBiConfig.getWritingScene()) // 写作场景（government:政务、media:传媒、market:营销，office：办公,custom:自定义）
                        .setWritingStyle(request.getDocumentType())  // 写作文体() 报告通报等
                        .setDistributeWriting(false)    //是否为分步骤写作
                        .setStep("Writing")     //分步骤写作步骤：OutlineGenerate:大纲生成、MiniDocSummary:摘编、Writing:写作
                        .setLanguage(aiMiaoBiConfig.getLanguage()) // en zh
                        .setGcNumberSize(aiMiaoBiConfig.getGcNumberSize()) // 写作的篇数
                        .setGcNumberSizeTag( wordCount ); // 文章篇幅（300 字左右、600 字左右、1000 字左右、2000 字左右等）

                
                // 设置流式返回
                RuntimeOptions runtime = new RuntimeOptions();
                runtime.setAutoretry(false);
                
                log.info("开始调用妙笔API...");
                
                // 直接调用SDK，让异常包含流式数据
                try {
                    RunWritingV2Response response = aiMiaoBiClient.runWritingV2WithOptions(writeRequest, runtime);

                    // 如果没有异常，说明是同步响应
                    log.info("API调用成功，响应状态: {}", response.getStatusCode());
                    emitter.send(SseEmitter.event()
                        .name("success")
                        .data("智能写作任务已提交，请求ID：" + response.getBody().getRequestId()));
                    emitter.complete();
                    
                } catch (Exception e) {
                    // 这里的异常实际包含了流式数据
                    String errorMessage = e.getMessage();
                    log.info("SDK返回流式数据（通过异常传递），消息长度: {}", errorMessage != null ? errorMessage.length() : 0);
                    
                    if (errorMessage != null && errorMessage.contains("data:")) {
                        // 解析并实现打字机效果
                        simulateTypingEffect(errorMessage, emitter);
                    } else {
                        log.error("未找到流式数据，这是真正的错误: {}", errorMessage);
                        emitter.completeWithError(e);
                    }
                }
                
            } catch (Exception e) {
                log.error("智能写作流式返回失败", e);
                try {
                    emitter.send(SseEmitter.event()
                        .name("error")
                        .data("智能写作失败：" + e.getMessage()));
                    emitter.completeWithError(e);
                } catch (IOException ioException) {
                    log.error("发送错误消息失败", ioException);
                }
            }
        });
        
        return emitter;
    }
    
    /**
     * 模拟打字机效果的流式传输
     */
    private void simulateTypingEffect(String streamData, SseEmitter emitter) {
        try {
            log.info("开始模拟打字机效果的流式传输...");
            
            // 提取最终的完整文本内容
            String fullText = extractFinalTextContent(streamData);
            if (fullText == null || fullText.length() < 10) {
                log.warn("无法提取有效文本内容，回退到原始流式转发");
                forwardOriginalStreamData(streamData, emitter);
                return;
            }
            
            log.info("提取到完整文本，长度: {}, 开始打字机效果传输", fullText.length());
            
            // 按字符逐个发送，模拟打字机效果
            StringBuilder currentText = new StringBuilder();
            int charsPerBatch = 2; // 每次发送2个字符
            int delayMs = 50; // 每批间隔50毫秒
            
            for (int i = 0; i < fullText.length(); i += charsPerBatch) {
                int endIndex = Math.min(i + charsPerBatch, fullText.length());
                String batch = fullText.substring(i, endIndex);
                currentText.append(batch);
                
                // 构造流式数据格式
                JSONObject eventData = new JSONObject();
                JSONObject header = new JSONObject();
                header.put("Event", "task-progress-generating");
                
                JSONObject payload = new JSONObject();
                JSONObject output = new JSONObject();
                output.put("Text", currentText.toString());
                payload.put("Output", output);
                
                eventData.put("Header", header);
                eventData.put("Payload", payload);
                
                // 发送数据
                emitter.send(SseEmitter.event()
                    .name("task-progress-generating")
                    .data(eventData.toString()));
                
                log.debug("发送打字机数据，当前长度: {}", currentText.length());
                
                // 延迟
                if (endIndex < fullText.length()) {
                    try {
                        Thread.sleep(delayMs);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        log.warn("打字机效果被中断");
                        break;
                    }
                }
            }
            
            // 发送完成事件
            JSONObject finalEvent = new JSONObject();
            JSONObject finalHeader = new JSONObject();
            finalHeader.put("Event", "task-progress-completed");
            
            JSONObject finalPayload = new JSONObject();
            JSONObject finalOutput = new JSONObject();
            finalOutput.put("Text", fullText);
            finalPayload.put("Output", finalOutput);
            finalPayload.put("End", true);
            
            finalEvent.put("Header", finalHeader);
            finalEvent.put("Payload", finalPayload);
            
            emitter.send(SseEmitter.event()
                .name("task-progress-completed")
                .data(finalEvent.toString()));
            
            emitter.complete();
            log.info("✅ 打字机效果流式传输完成，总字符数: {}", fullText.length());
            
        } catch (Exception e) {
            log.error("打字机效果传输失败", e);
            try {
                emitter.completeWithError(e);
            } catch (Exception ex) {
                log.error("完成错误状态失败", ex);
            }
        }
    }
    
    /**
     * 从流式数据中提取最终的完整文本内容
     */
    private String extractFinalTextContent(String streamData) {
        try {
            // 按行分割
            String[] lines = streamData.split("\n");
            String longestText = "";
            
            for (String line : lines) {
                if (line.startsWith("data:")) {
                    String jsonData = line.substring(5);
                    try {
                        JSONObject data = JSONUtil.parseObj(jsonData);
                        if (data.containsKey("Payload")) {
                            JSONObject payload = data.getJSONObject("Payload");
                            if (payload.containsKey("Output")) {
                                JSONObject output = payload.getJSONObject("Output");
                                if (output.containsKey("Text")) {
                                    String text = output.getStr("Text");
                                    if (text != null && text.length() > longestText.length()) {
                                        longestText = text;
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.debug("解析JSON失败: {}", e.getMessage());
                    }
                }
            }
            
            return longestText.length() > 10 ? longestText : null;
            
        } catch (Exception e) {
            log.error("提取文本内容失败", e);
            return null;
        }
    }
    
    /**
     * 原始流式数据转发（备用方案）
     */
    private void forwardOriginalStreamData(String streamData, SseEmitter emitter) {
        try {
            String[] lines = streamData.split("\n");
            
            for (String line : lines) {
                if (line.startsWith("data:")) {
                    String jsonData = line.substring(5);
                    emitter.send(SseEmitter.event().data(jsonData));
                } else if (line.startsWith("event:")) {
                    String eventName = line.substring(6);
                    emitter.send(SseEmitter.event().name(eventName));
                }
            }
            
            emitter.complete();
            log.info("✅ 原始流式数据转发完成");
            
        } catch (Exception e) {
            log.error("原始流式数据转发失败", e);
            try {
                emitter.completeWithError(e);
            } catch (Exception ex) {
                log.error("完成错误状态失败", ex);
            }
        }
    }

    @Override
    public SseEmitter runContinueContentStream(DocumentOperationRequestDto request) throws Exception {
        String content = request.getSelectedText();
        log.info("开始续写内容流式返回，原内容长度：{}", content != null ? content.length() : 0);
        
        SseEmitter emitter = new SseEmitter(300000L);
        
        CompletableFuture.runAsync(() -> {
            try {
                RunContinueContentRequest continueRequest = new RunContinueContentRequest()
                        .setWorkspaceId(aiMiaoBiConfig.getWorkspaceId())
                        .setContent(content);

                RuntimeOptions runtime = new RuntimeOptions();
                runtime.setAutoretry(false);
                
                log.info("开始调用续写API...");
                
                try {
                    RunContinueContentResponse response = aiMiaoBiClient.runContinueContentWithOptions(continueRequest, runtime);
                    
                    log.info("续写API调用成功，响应状态: {}", response.getStatusCode());
                    
                    emitter.send(SseEmitter.event()
                        .name("success")
                        .data("续写任务已提交，任务ID：" + response.getBody().getRequestId()));
                    
                    emitter.complete();
                } catch (Exception e) {
                    String errorMessage = e.getMessage();
                    log.info("SDK返回续写流式数据（通过异常传递），消息长度: {}", errorMessage != null ? errorMessage.length() : 0);
                    
                    if (errorMessage != null && errorMessage.contains("data:")) {
                        // 解析并实现打字机效果
                        simulateTypingEffect(errorMessage, emitter);
                    } else {
                        log.error("续写未找到流式数据，这是真正的错误: {}", errorMessage);
                        emitter.completeWithError(e);
                    }
                }
                
            } catch (Exception e) {
                log.error("续写内容流式返回失败", e);
                try {
                    emitter.send(SseEmitter.event()
                        .name("error")
                        .data("续写内容失败：" + e.getMessage()));
                    emitter.completeWithError(e);
                } catch (IOException ioException) {
                    log.error("发送续写错误消息失败", ioException);
                }
            }
        });
        
        return emitter;
    }

    @Override
    public SseEmitter runTextPolishingStream(DocumentOperationRequestDto request) throws Exception {
        String content = request.getSelectedText();
        log.info("开始文本w流式返回，内容长度：{}", content != null ? content.length() : 0);
        SseEmitter emitter = new SseEmitter(300000L);
        CompletableFuture.runAsync(() -> {
            try {
                RunTextPolishingRequest polishRequest = new RunTextPolishingRequest()
                        .setWorkspaceId(aiMiaoBiConfig.getWorkspaceId())
                        .setContent(content);

                RuntimeOptions runtime = new RuntimeOptions();
                runtime.setAutoretry(false);
                log.info("开始调用润色API...");
                try {
                    RunTextPolishingResponse response = aiMiaoBiClient.runTextPolishingWithOptions(polishRequest, runtime);
                    log.info("润色API调用成功，响应状态: {}", response.getStatusCode());
                    emitter.send(SseEmitter.event()
                        .name("success")
                        .data("润色任务已提交，任务ID：" + response.getBody().getRequestId()));
                    emitter.complete();
                } catch (Exception e) {
                    String errorMessage = e.getMessage();
                    log.info("SDK返回润色流式数据（通过异常传递），消息长度: {}", errorMessage != null ? errorMessage.length() : 0);
                    if (errorMessage != null && errorMessage.contains("data:")) {
                        // 解析并实现打字机效果
                        simulateTypingEffect(errorMessage, emitter);
                    } else {
                        log.error("润色未找到流式数据，这是真正的错误: {}", errorMessage);
                        emitter.completeWithError(e);
                    }
                }
                
            } catch (Exception e) {
                log.error("文本润色流式返回失败", e);
                try {
                    emitter.send(SseEmitter.event()
                        .name("error")
                        .data("文本润色失败：" + e.getMessage()));
                    emitter.completeWithError(e);
                } catch (IOException ioException) {
                    log.error("发送润色错误消息失败", ioException);
                }
            }
        });
        
        return emitter;
    }

    /**
     * 将DocumentFormFieldsDto转换为Map<String, String>
     */
    private Map<String, String> convertFieldsToMap(DocumentFormFieldsDto fields) {
        Map<String, String> fieldsMap = new HashMap<>();
        
        if (fields == null) {
            return fieldsMap;
        }

        try {
            Field[] declaredFields = DocumentFormFieldsDto.class.getDeclaredFields();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                Object value = field.get(fields);

                if (value != null && StrUtil.isNotBlank(value.toString())) {
                    String fieldName = field.getName();
                    
                    // 使用英文字段名作为key
                    fieldsMap.put(fieldName, value.toString());
                }
            }
        } catch (Exception e) {
            log.error("转换字段为Map失败", e);
        }

        return fieldsMap;
    }

    /**
     * 构建文章内容
     */
    private String buildArticleContent(String documentType, DocumentFormFieldsDto fields) {
        if (fields == null) {
            return "请生成一份" + documentType;
        }

        StringBuilder sb = new StringBuilder();
        sb.append("请生成一份").append(documentType).append("，要求如下：");

        try {
            Field[] declaredFields = DocumentFormFieldsDto.class.getDeclaredFields();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                Object value = field.get(fields);

                if (value != null && StrUtil.isNotBlank(value.toString())) {
                    String fieldName = field.getName();
                    String chineseName = FIELD_NAME_MAP.get(fieldName);

                    if (chineseName != null) {
                        sb.append(chineseName).append("：").append(value).append("；");
                    }
                }
            }
        } catch (Exception e) {
            log.error("构建文章内容失败", e);
        }

        return sb.toString();
    }
}